package com.foosun.core.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.Enumeration;

/**
 * org.apache.tools.zip
 * 压缩文件
 * @author pengli caiyunhang
 *
 */

public class ZipHelper {
	
	private static Log logger = LogFactory.getLog(ZipHelper.class);
	
	/**
	 * 解压文件（linux),解压到目的地址下
	 * @param zipFile
	 * @param descDir
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean unZipFiles(File zipFile,String descDir){
		
		File pathFile = new File(descDir);
		if(!pathFile.exists()){
			pathFile.mkdirs();
		}
		ZipFile zip;
		try {
			zip = new ZipFile(zipFile, "gbk"); //得到压缩文件
			for(Enumeration entries = zip.getEntries();entries.hasMoreElements();){
				ZipEntry entry = (ZipEntry)entries.nextElement();
				entry.setUnixMode(644);
				String zipEntryName = entry.getName();
				InputStream in = zip.getInputStream(entry);
				String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");
				//判断路径是否存在,不存在则创建文件路径
				File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
				if(!file.exists()){
					file.mkdirs();
				}
				//判断文件全路径是否为文件夹,如果是,上面已经上传,不需要解压
				if(new File(outPath).isDirectory()){
					continue;
				}
				
				OutputStream out = new FileOutputStream(outPath);
				byte[] buf = new byte[1024];
				int len;
				while((len=in.read(buf))>0){
					out.write(buf,0,len);
				}
				in.close();
				out.close();
			}
		} catch (IOException e) {
			logger.debug(e);
			return false;
		}
		
		return true;
		
	}
	
	/**
	 * 压缩文件夹
	 * @param inputFileName
	 * @param zipFileName
	 * @return
	 * @throws Exception
	 */
	public static OutputStream zip(String inputFileName, String zipFileName) throws Exception
    {
        return zip(zipFileName, new File(inputFileName));
    }
	
	
	
    private static OutputStream zip(String zipFileName, File inputFile) throws Exception
    {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                zipFileName));
        out.setEncoding("gbk");//解决linux乱码
        zip(out, inputFile,"");
        out.close();
        return out;
    }
    
    
    
    private static void zip(ZipOutputStream out, File f, String base) throws Exception
    {
        if (f.isDirectory())
        { // 判断是否为目录
            File[] fl = f.listFiles();
            ZipEntry zipEntry=new ZipEntry(base + System.getProperties().getProperty("file.separator"));
            zipEntry.setUnixMode(755);
            out.putNextEntry(zipEntry);
            base = base.length() == 0 ? "" : base + System.getProperties().getProperty("file.separator");
            for (int i = 0; i < fl.length; i++)
            {    
            	zip(out, fl[i], base + fl[i].getName());
            }
        }
        else
        { // 压缩目录中的所有文件
            ZipEntry zipEntry=new ZipEntry(base);
            zipEntry.setUnixMode(644);
            out.putNextEntry(zipEntry);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
            
            byte[] buffer = new byte[2048];
            int lengh = 0;
            while ((lengh = in.read(buffer,0,buffer.length)) != -1)
            {
                out.write(buffer,0,lengh);
            }
            in.close();
        }
    }
}
